import React from 'react';
import { Form, Input, Button, Card, Typography, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import store from "./store";

const { Title, Text } = Typography;

const Login = () => {
  const { loading, updates, login } = store();

  const navigate = useNavigate();

  // 处理登录
  const handleLogin = async (values) => {
    // 更新loading状态
    updates({
      loading: { login: true }
    });

    const param = {
      username: values.username,
      password: values.password
    };

    const result = await login(param);
  
    if (result.success) {
      message.success('登录成功');
      // 跳转到首页
      navigate('/');
    } else {
      message.error(result.message);
    }
  };

  return (
    <div className="flex min-h-screen justify-center items-center bg-gray-50">
      <div className="w-full max-w-md p-4">
        <Card className="w-full shadow-md">
          <div className="text-center mb-6">
            <Title level={2} className="mb-1">欢迎回来</Title>
            <Text type="secondary">请登录您的账号继续</Text>
          </div>

          <Form
            name="login_form"
            initialValues={{ remember: true }}
            onFinish={handleLogin}
            size="large"
            layout="vertical"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名或邮箱' }]}
            >
              <Input
                prefix={<UserOutlined className="text-gray-400" />}
                placeholder="用户名或邮箱"
                disabled={loading.login}
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined className="text-gray-400" />}
                placeholder="密码"
                disabled={loading.login}
              />
            </Form.Item>

            {/* <Form.Item>
              <div className="flex justify-between">
                <Link to="/forgot-password" className="text-blue-500 hover:text-blue-600">
                  忘记密码？
                </Link>
              </div>
            </Form.Item> */}

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="w-full"
                loading={loading.login}
              >
                登录
              </Button>
            </Form.Item>

            <div className="text-center">
              <Text type="secondary">
                还没有账号？ <Link to="/register" className="text-blue-500 hover:text-blue-600">立即注册</Link>
              </Text>
            </div>
          </Form>
        </Card>
      </div>
    </div>
  );
};

// 使用App组件包装Login组件
const LoginWithApp = () => (
  <Login />
);

export default LoginWithApp;